package com.exam.controller;


import com.exam.entity.Booktype;
import com.exam.service.BooktypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author D
 * @since 2023-03-18 10:53:40
 */
@RestController
@RequestMapping("/booktype")
public class BooktypeController {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    BooktypeService booktypeService;

    /**
     * 获取图书分类列表，如果redis中有缓存则直接返回，否则从数据库中获取并加入redis缓存
     *
     * @return 返回图书分类列表
     */
    @RequestMapping("/getList")
    public Object getList() {
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        List<Booktype> booktypeList = (List<Booktype>) opsForValue.get("booktypeList");
        if (booktypeList != null) {
            return booktypeList;
        }
        booktypeList = booktypeService.list();
        opsForValue.set("booktypeList", booktypeList);
        return booktypeList;

    }

    /**
     * 根据id删除指定的图书分类，同时删除redis中的缓存
     *
     * @param id 要删除的图书分类的id
     * @return 返回删除结果
     */
    @RequestMapping("/deleteById")
    public Object deleteById(Integer id) {
        booktypeService.removeById(id);
        redisTemplate.delete("booktypeList");
        return "删除成功";
    }

    /**
     * 根据id修改指定的图书分类名称，同时删除redis中的缓存
     *
     * @param id   要修改的图书分类的id
     * @param name 新的图书分类名称
     * @return 返回修改结果
     */
    @RequestMapping("updateById")
    public Object updateById(Integer id, String name) {
        Booktype booktype = booktypeService.getById(id);
        booktype.setName(name);
        booktype.setUpdatetime(new Date(System.currentTimeMillis()));
        booktypeService.updateById(booktype);
        redisTemplate.delete("booktypeList");
        return "修改成功";
    }

    /**
     * 新增一条图书分类记录，同时删除redis中的缓存
     *
     * @param name 新的图书分类名称
     * @return 返回添加结果
     */
    @RequestMapping("newType")
    public Object newType(String name) {
        Booktype booktype = new Booktype();
        booktype.setName(name);
        booktype.setCreatetime(new Date());
        booktype.setUpdatetime(new Date());
        booktypeService.save(booktype);
        redisTemplate.delete("booktypeList");
        return "添加成功";
    }

}

